<template>
  <div class="survey-save-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/surveyList' }">查勘任务列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加查勘信息</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- <h1 class="page-title">添加查勘信息</h1> -->
    </div>

    <!-- 查勘信息表单 -->
    <el-card class="form-card" shadow="hover">
      <el-form ref="surveyFormRef" :model="surveyForm" :rules="formRules" label-width="180px" class="survey-form"
        size="medium" @submit.prevent="handleSubmit">
        <!-- 报案号 -->
        <el-form-item label="报案号" prop="reportNo">
          <el-input v-model="surveyForm.reportNo" placeholder="请输入关联的报案号（如REP2023091900001，非必填）" clearable
            max-length="50" readonly />
        </el-form-item>

        <!-- 查勘员工号 -->
        <el-form-item label="查勘员工号" prop="surveyInWorkNo">
          <el-input v-model="surveyForm.surveyInWorkNo" placeholder="查勘员工号" clearable max-length="50" readonly />
        </el-form-item>


        <!-- 查勘现场照片上传 -->
        <el-form-item label="查勘现场照片">
          <el-upload v-model:file-list="uploadData.fileList" :action="`${BASE_URL}/aiSurveyReport/singleImage`"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
            :on-success="handleUploadSuccess" :before-upload="beforeAvatarUpload" :on-exceed="handleExceed" limit="3"
            :disabled="submitLoading">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>

          <!-- 图片预览弹窗 -->
          <el-dialog v-model="uploadData.dialogVisible" title="图片预览" width="80%">
            <img :src="uploadData.dialogImageUrl" alt="预览图片"
              style="width: 100%; max-height: 80vh; object-fit: contain" />
          </el-dialog>
          <el-form-item__help>
            支持JPG/PNG格式，最多上传3张，单张不超过2MB（非必填）
          </el-form-item__help>
        </el-form-item>

        <!-- 损失类型 -->
        <el-form-item label="损失类型" prop="lossType" required>
          <el-select v-model="surveyForm.lossType" placeholder="请选择损失类型" clearable>
            <el-option label="作物损失" value="1" />
            <el-option label="牲畜损失" value="2" />
            <el-option label="农机损失" value="3" />
            <el-option label="其他损失" value="4" />
          </el-select>
        </el-form-item>

        <!-- 受灾面积 -->
        <el-form-item label="受灾面积（亩）" prop="disasterArea">
          <el-input v-model.number="surveyForm.disasterArea" placeholder="请输入受灾面积（保留2位小数，非必填）" clearable type="number"
            step="0.01" min="0" />
        </el-form-item>

        <!-- 损失数量 -->
        <el-form-item label="损失数量" prop="disasterMount">
          <el-input v-model="surveyForm.disasterMount" placeholder="请输入损失数量（如10头、5台，非必填）" clearable max-length="100" />
        </el-form-item>

        <!-- 受灾原因 -->
        <el-form-item label="受灾原因" prop="disasterReason" required>
          <el-input v-model="surveyForm.disasterReason" placeholder="请详细描述受灾原因" clearable max-length="255"
            type="textarea" rows="3" />
        </el-form-item>

        <!-- 实际查勘地点 -->
        <el-form-item label="实际查勘地点" prop="surveyAddress" required>
          <el-input v-model="surveyForm.surveyAddress" placeholder="省/市/县/乡镇/具体位置" clearable max-length="255" />
        </el-form-item>

        <!-- 预估损失金额 -->
        <el-form-item label="预估损失金额（元）" prop="surveyMoney" required>
          <el-input v-model.number="surveyForm.surveyMoney" placeholder="请输入预估损失金额" clearable type="number" step="0.01"
            min="0" />
        </el-form-item>

        <!-- 查勘状态 -->
        <el-form-item label="查勘状态" prop="surveyStatus" required>
          <el-input v-model="surveyForm.surveyStatus" value="已查勘" readonly disabled />
        </el-form-item>

        <!-- 查勘开始时间 -->
        <el-form-item label="查勘开始时间" prop="surverStartTime">
          <el-date-picker v-model="surveyForm.surverStartTime" type="datetime" placeholder="选择查勘开始时间"
            value-format="YYYY-MM-DD HH:mm:ss" clearable />
        </el-form-item>

        <!-- 查勘结束时间 -->
        <el-form-item label="查勘结束时间" prop="surverEndTime">
          <el-date-picker v-model="surveyForm.surverEndTime" type="datetime" placeholder="选择查勘结束时间"
            value-format="YYYY-MM-DD HH:mm:ss" clearable :disabled-date="disabledEndDate" />
        </el-form-item>

        <!-- 表单操作按钮 -->
        <el-form-item class="form-btn-group">
          <el-button type="primary" icon="Check" @click="handleSubmit" :loading="submitLoading" native-type="submit">
            保存查勘信息
          </el-button>
          <el-button type="default" icon="ArrowLeft" @click="$router.push('/surveyList')" class="ml-4">
            返回列表
          </el-button>
          <el-button type="danger" icon="RefreshLeft" @click="handleReset" class="ml-4" :disabled="submitLoading">
            重置表单
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
// ==================== 导入依赖 ====================
import { ref, reactive, onMounted, toRaw } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import router from '@/router'
import hxxp from '@/utils/hxxp.js'


// ==================== 常量配置 ====================
const BASE_URL = 'http://localhost:9000'
const saveUrl = `${BASE_URL}/aiSurveyReport/save`

// ==================== 响应式状态 ====================
// 表单引用和加载状态
const surveyFormRef = ref(null)
const submitLoading = ref(false)



// 图片上传相关状态
const uploadData = reactive({
  fileList: [],
  dialogImageUrl: '',
  dialogVisible: false
})

// 表单数据模型
const surveyForm = reactive({
  surveyId: '',
  reportNo: '',
  surveyInWorkNo: '',
  surveyPhoto: '',
  lossType: '',
  disasterArea: '',
  disasterMount: '',
  disasterReason: '',
  surveyAddress: '',
  surveyMoney: '',
  surveyStatus: '3',
  surverStartTime: '',
  surverEndTime: ''
})

// ==================== 验证函数 ====================
/**
 * 验证金额格式
 */
const validateMoney = (rule,value, callback) => {
  if (value === null || value === undefined || value === '') {
    callback()
    return
  }
  const reg = /^\d+(\.\d{1,2})?$/
  if (!reg.test(value)) {
    callback(new Error('金额需保留1-2位小数（如100.00）'))
  } else {
    callback()
  }
}

/**
 * 验证查勘开始时间
 */
const validateStartTime = (rule,value, callback) => {
  if (!value) {
    callback(new Error('已查勘状态需选择开始时间'))
  } else {
    callback()
  }
}

/**
 * 验证查勘结束时间
 */
const validateEndTime = (rule, value, callback) => {
  if (!value) {
    callback(new Error('已查勘状态需选择结束时间'))
  } else if (surveyForm.surverStartTime && new Date(value) <= new Date(surveyForm.surverStartTime)) {
    callback(new Error('结束时间需晚于开始时间'))
  } else {
    callback()
  }
}

// ==================== 表单验证规则 ====================
const formRules = reactive({
  reportNo: [
    { pattern: /^REP\d{11,}$/, message: '报案号格式应为REP开头+11位以上数字', trigger: 'blur' },
    { max: 50, message: '报案号长度不能超过50个字符', trigger: 'blur' }
  ],
  surveyInWorkNo: [
    { pattern: /^[A-Za-z0-9]{1,50}$/, message: '本司工号仅支持字母和数字', trigger: 'blur' },
    { max: 50, message: '本司工号长度不能超过50个字符', trigger: 'blur' }
  ],
  lossType: [
    { required: true, message: '请选择损失类型', trigger: 'change' }
  ],
  disasterReason: [
    { required: true, message: '请描述受灾原因', trigger: 'blur' },
    { max: 255, message: '受灾原因长度不能超过255个字符', trigger: 'blur' }
  ],
  surveyAddress: [
    { required: true, message: '请输入实际查勘地点', trigger: 'blur' },
    { max: 255, message: '查勘地点长度不能超过255个字符', trigger: 'blur' }
  ],
  surveyMoney: [
    { required: true, message: '请输入预估损失金额', trigger: 'blur' },
    { type: 'number', message: '金额必须为数字', trigger: 'blur' },
    { validator: validateMoney, trigger: 'blur' }
  ],
  surveyStatus: [
    { required: true, message: '请选择查勘状态', trigger: 'change' }
  ],
  surverStartTime: [
    { required: true, message: '已查勘状态需选择开始时间', trigger: 'change' },
    { validator: validateStartTime, trigger: 'change,blur' }
  ],
  surverEndTime: [
    { required: true, message: '已查勘状态需选择结束时间', trigger: 'change' },
    { validator: validateEndTime, trigger: 'change,blur' }
  ]
})

// ==================== 事件处理函数 ====================

// ==================== 生命周期钩子 ====================
/**
 * 页面初始化
 */
onMounted(() => {
  const reportNo = router.currentRoute.value.query.reportNo
  const surveyInWorkNo = router.currentRoute.value.query.surveyWorkNo
  const surveyId = router.currentRoute.value.query.surveyId

  if (reportNo) {
    surveyForm.reportNo = reportNo
  }
  if (surveyInWorkNo) {
    surveyForm.surveyInWorkNo = surveyInWorkNo
  }
  if (surveyId) {
    surveyForm.surveyId = surveyId
  }
})


// ==================== 图片上传相关函数 ====================
/**
 * 上传前验证
 */
const beforeAvatarUpload = (rawFile) => {
  const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
  if (!isImage) {
    ElMessage.error('请上传JPG或PNG格式的图片！')
    return false
  }
  const isLt2M = rawFile.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

/**
 * 上传成功处理
 */
const handleUploadSuccess = (response, uploadFile, uploadFiles) => {
  console.log('图片上传后端响应：', response)
  const successCode = [200, 100200]
  if (response && successCode.includes(response.code) && response.data) {
    uploadFile.url = response.data
    const urlArray = uploadFiles.filter(file => file.url).map(file => file.url)
    surveyForm.surveyPhoto = urlArray.join(',')
    ElMessage.success(response.msg || '图片上传成功')
  } else {
    uploadData.fileList = uploadData.fileList.filter(file => file.uid !== uploadFile.uid)
    ElMessage.error(response?.msg || '图片上传失败：后端未返回有效地址')
  }
}

/**
 * 删除图片处理
 */
const handleRemove = async (uploadFile, uploadFiles) => {
  if (uploadFile.url) {
    try {
      const res = await hxxp.delete('/aiSurveyReport/deleteImage', {
        params: { url: uploadFile.url }
      })
      if (res && [200, 100200].includes(res.code)) {
        ElMessage.success(res.msg || '图片已删除')
      } else {
        ElMessage.warning(res?.msg || '图片删除失败，已保留本地记录')
      }
    } catch (error) {
      console.error('删除图片失败：', error)
      ElMessage.warning('删除图片时发生网络错误，请重试')
    }
  }
  uploadData.fileList = uploadFiles
  const urlArray = uploadFiles.filter(file => file.url).map(file => file.url)
  surveyForm.surveyPhoto = urlArray.join(',')
}

/**
 * 图片预览处理
 */
const handlePictureCardPreview = (uploadFile) => {
  uploadData.dialogImageUrl = uploadFile.url
  uploadData.dialogVisible = true
}

/**
 * 超出限制处理
 */
const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(`最多只能上传3张图片，本次选择了${files.length}张，已忽略多余文件`)
}

// ==================== 工具函数 ====================
/**
 * 结束时间禁用逻辑
 */
const disabledEndDate = (time) => {
  if (surveyForm.surverStartTime) {
    return time.getTime() <= new Date(surveyForm.surverStartTime).getTime()
  }
  return false
}

// ==================== 表单操作函数 ====================
/**
 * 表单提交处理
 */
const handleSubmit = async () => {
  const formRef = surveyFormRef.value
  if (!formRef) {
    ElMessage.error('表单初始化失败，请刷新页面重试')
    return
  }

  try {
    // 开启加载状态
    submitLoading.value = true

    // 处理提交数据（过滤空值）
    const saveData = toRaw(surveyForm)
    Object.keys(saveData).forEach(key => {
      if (saveData[key] === '' || saveData[key] === null || saveData[key] === undefined) {
        delete saveData[key]
      }
    })
    console.log('提交给save接口的数据：', saveData)

    // 调用保存接口
    const saveResponse = await axios({
      method: 'PUT',
      url: saveUrl,
      data: saveData,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      timeout: 30000
    })

    // 处理保存结果
    const successCode = [200, 100200]
    if (saveResponse.data && successCode.includes(saveResponse.data.code)) {
      ElMessage.success('查勘信息保存成功！')
      setTimeout(() => {
        router.push('/surveyList')
      }, 1000)
    } else {
      ElMessage.error(`查勘信息保存失败：${saveResponse.data?.msg || '未知错误'}`)
    }

  } catch (error) {
    // 错误处理
    if (error.response) {
      ElMessage.error(`请求失败：${error.response.status} ${error.response.statusText}`)
      console.error('请求错误详情：', error.response.data)
    } else if (error.request) {
      ElMessage.error(`网络异常：无法连接到后端服务（${BASE_URL}），请检查服务是否启动`)
    } else {
      ElMessage.error(`提交失败：${error.message || '未知错误'}`)
    }
    console.error('提交错误完整信息：', error)
  } finally {
    submitLoading.value = false
  }
}

/**
 * 表单重置处理
 */
const handleReset = () => {
  const formRef = surveyFormRef.value
  if (formRef) {
    formRef.resetFields()
  }
  uploadData.fileList = []
  surveyForm.surveyPhoto = ''
  ElMessage.success('表单已重置')
}


</script>

<style scoped>
/* ==================== 页面布局样式 ==================== */
.survey-save-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 8px 0;
}

/* ==================== 表单样式 ==================== */
.form-card {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.survey-form {
  padding: 24px;
}

.form-btn-group {
  margin-top: 16px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

/* ==================== 上传组件样式 ==================== */
.el-upload--picture-card {
  width: 120px;
  height: 120px;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;
}

/* ==================== 响应式样式 ==================== */
@media (max-width: 768px) {
  .survey-save-page {
    padding: 12px 8px;
  }

  .survey-form {
    padding: 16px;
  }

  .form-btn-group {
    flex-direction: column;
    align-items: flex-start;
  }

  .form-btn-group .el-button {
    width: 100%;
    margin-bottom: 8px;
    margin-left: 0 !important;
  }
}
</style>